﻿// See https://aka.ms/new-console-template for more information

using Microsoft.AspNetCore.SignalR.Client;
string SignalR_Port = Environment.GetEnvironmentVariable("SignalR_Port", EnvironmentVariableTarget.Machine);//ipconfig为电脑环境变量名
HubConnection connection = new HubConnectionBuilder().
  WithUrl(SignalR_Port).Build();

//断线重连
connection.Closed += async (Exception? error) =>
{
    await Task.Delay(new Random().Next(0, 5) * 1000);
    await connection.StartAsync();
};
//注册服务端响应  被服务端调用
connection.On<string>("CallByHub", (string str) =>
{

    Console.WriteLine(str);

});
//连接
await connection.StartAsync();


//调用服务端-1
await connection.SendAsync("CallByClient", "我是客户端");
//调用服务端有返回值-2
var msg = await connection.InvokeAsync<string>("CallByClientWithReturnValue", "我是客户端2");
Console.WriteLine(msg);


//调用服务端调用-3
await connection.SendAsync("CallClient", "调用客户端方法");
Console.ReadLine();

//调用服务端调用-5 除之身以为发送
await connection.SendAsync("CallOtherClients", "调用客户端方法");

//调用服务端-6  加入分组 然后按组发送
await connection.SendAsync("RegisterToGroup", "grp1");
await connection.SendAsync("SendToGroup", "grp1");

//调用服务端-7  指定id发送
await connection.SendAsync("SendToClient", connection.ConnectionId);